package com.acxy.ants.core.proxy;

import com.acxy.ants.common.kit.CollectionKit;
import com.acxy.ants.core.Invocation;
import com.acxy.ants.core.annotation.Aop;
import com.acxy.ants.core.annotation.Uop;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-06-07
 */
public class AopInvocation {

    private AopInvocation(){}

    public static Object handler(Object target, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        //=================== 处理AOP ======================
        Aop methodAop = method.getAnnotation(Aop.class); //取方法上面的AOP注解
        Uop methodUop = method.getAnnotation(Uop.class); //取类上面的UOP注解
        Aop classAop = target.getClass().getAnnotation(Aop.class); //取类上面的AOP注解
        Object result = null;
        if (methodAop != null || classAop != null || methodUop != null) {
            //方法上面的AOP注解优先级大于类上面的优先级
            Class[] values = CollectionKit.union(classAop == null ? null : classAop.value(), methodAop == null ? null : methodAop.value());
            if (values != null && values.length > 0) {
                values = CollectionKit.minus(values, methodUop == null ? null : methodUop.value());
            }
            Invocation cinvo = new Invocation(target, method, args, 0, values); //从0开始调用
            result = cinvo.invoke();
        } else {
            result = method.invoke(target, args);
        }
        return result;
    }
}
